<?php
namespace App\Services\Square;

use App\Models\Member\Member;
use App\Models\Member\Like;
use App\Models\Member\Follow;
use App\Models\Store\Store;
use App\Models\News\News;
use App\Models\Activity\Activity;
use App\Models\Common\City;
use App\Models\Common\School;
use App\Services\Member\MemberService;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Vod\Vod;

use App\Services\Com\UtilService;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

/***
 * 人物广场
 * 
 **/
class PopstartService
{
    /**
     * 广场的校友列表
     *  'uuid'=>"acbb-131231", //用户uuid
        'username'=>"some one name",//用户名
        'avatar'=>"http://xxx.xxx/jpg",//用户头像
        'school_name'=>"school base",//学校
        'country'=>'US',//国家名称
        'country_flag'=>'https://xxx.lai.com/123.png',//国家国旗
        'attention'=>1, //我对此人的关注状态 1是已经关注，0是未关注
        'fans_count'=>123,//粉丝数
     **/
    public static function school(array $param = [], $member_uuid = ''){

        $where[] = ['school_uuid', '=', $param['school_uuid']];
        // $where[] = ['state', '=', '200'];
        
        $res = Member::where($where)
            ->with(['school' => function ($query) {
                return $query->select(['uuid', 'name']);
            }])
            ->with(['country' => function ($query) {
                return $query->select(['uuid', 'name', 'nationalflag']);
            }])
            ->with(['isFollow' => function ($query) {
                return $query->select(['member_uuid', 'followed_member_uuid', 'is_muted']);
            }])
            ->select('uuid','nickname','avatar_url','nickname', 'school_uuid', 'country_uuid', 'state')
            ->where('uuid', '<>', $member_uuid)
            ->orderBy('id','desc')->paginate($param['limit']);

        $res_arr = $res->toArray();
        
        $list = null;
        $count = count($res_arr['data']);
        //大于6个或者传来的条数 或者是列表
        if($count >= $param['limit'] || isset($param['is_page']) ){
            foreach ($res_arr['data'] as $key => $value) {
                $follow_where = null;
                $follow_where[] = ['member_uuid', '=', $member_uuid];
                $follow_where[] = ['followed_member_uuid', '=', $value['uuid']];
                $follow_count = Follow::where($follow_where)->count();
                $list[] = [
                    'uuid'=>$value['uuid'], //用户uuid
                    'username'=>$value['nickname'],//用户名
                    'im_username'=>UtilService::memberUuidToImAccount($value['uuid']),//用户名
                    'state'=>$value['state'],//用户状态
                    'avatar'=>$value['avatar_url'],//用户头像
                    'school_name'=>$value['school']['name'] ?? '',//学校
                    'country'=>$value['country']['name'] ?? '',//国家名称
                    'country_flag'=>$value['country']['nationalflag'] ?? '',//国家国旗
                    'attention'=>$follow_count >=1 ? 1 : 0,//1是已经关注0，是未关注
                    'fans_count'=>MemberService::followCount($value['uuid']),//粉丝数
                ];
            }
        }
        //返回处理，有分页或者没分页
        if(isset($param['is_page'])){
            $data['list'] = $list;
            unset($res_arr['data']);
            $data['page_info'] = $res_arr;
            return $data;
        }else{
            return $list;
        }
    }

    /**
     * 本地
     * @param
     * $param['city_id']
     * $param['latitude'] = $latitude; 纬度
     * $param['longitude'] = $longitude; 经度
     * $param['member_uuid'] = $member_uuid;
     * $param['limit'] = (int)$request->get('limit',6);
     * 
     * @return 
     *  'uuid'=>"acbb-131231", //用户uuid
        'username'=>"some one name",//用户名
        'avatar'=>"http://xxx.xxx/jpg",//用户头像
        'city_id'=>$value['city_id'],//城市id
        'country'=>'US',//国家名称
        'country_flag'=>'https://xxx.lai.com/123.png',//国家国旗
        'attention'=>1, //我对此人的关注状态 1是已经关注，0是未关注
        'fans_count'=>123,//粉丝数
     **/
    public static function local(array $param = [], $member_uuid = ''){
        $city_id = 0;

        //经纬优先
        if(!empty($param['latitude']) && !empty($param['longitude'])){
            $geo = UtilService::getRegeo($param['longitude'].','.$param['latitude'], 'all');
            if(isset($geo['infocode']) && $geo['infocode'] == 10000){
                $city_id = $geo['regeocode']['addressComponent']['adcode'];
            }
        }elseif(!empty($param['city_id'])){
            $city_id = $param['city_id'];
        }

// DB::connection()->enableQueryLog();

        $where[] = ['uuid', '<>', $member_uuid];
        $model = Member::where($where);

        //城市如果没有就返回空隐藏
        if(empty($city_id)){
            return null;
        }else{
            $cidy_arr = UtilService::getCityId($city_id);
            $cidy_arr_str = implode(',', $cidy_arr);
            $cidy_arr_str2 = $cidy_arr_str;

            $model = $model->Where(function($query)use ($cidy_arr){
                {
                    return $query->orWhereIn('province_id', $cidy_arr)
                        ->orWhereIn('online_city_id', $cidy_arr)
                        ->orWhereIn('area_id', $cidy_arr)
                        ->orWhereIn('city_id', $cidy_arr);
                }
            });
        }        

        //取带城市id的
        $res = $model->with(['country' => function ($query) {
                return $query->select(['uuid', 'name', 'nationalflag']);
            }])
            ->with(['isFollow' => function ($query) {
                return $query->select(['member_uuid', 'followed_member_uuid', 'is_muted']);
            }])
            ->select('uuid','nickname','avatar_url','nickname', 'city_id', 'country_uuid', 'state')
            ->orderBy('id','desc')
            ->paginate($param['limit']);
        $res_arr = $res->toArray();
// $log = DB::getQueryLog();
// var_dump($log, $res_arr);
// die;
        //城市id没有就随机推
        if( $res_arr['total'] <= 0 || $res_arr['total'] < $param['limit'] ){
            
            // $res = Member::where($where_rand)
            // ->with(['country' => function ($query) {
            //     return $query->select(['uuid', 'name', 'nationalflag']);
            // }])
            // ->with(['isFollow' => function ($query) {
            //     return $query->select(['member_uuid', 'followed_member_uuid', 'is_muted']);
            // }])
            // ->select('uuid','nickname','avatar_url','nickname', 'city_id', 'country_uuid', 'state')
            // ->orderBy(\DB::raw('RAND()'))->paginate($param['limit']);
            // $res_arr = $res->toArray();
        }

        $list = null;
        foreach ($res_arr['data'] as $key => $value) {
            $follow_where = null;
            $follow_where[] = ['member_uuid', '=', $member_uuid];
            $follow_where[] = ['followed_member_uuid', '=', $value['uuid']];
            $follow_count = Follow::where($follow_where)->count();

            $list[] = [
                'uuid'=>$value['uuid'], //用户uuid
                'username'=>$value['nickname'],//用户名
                'im_username'=>UtilService::memberUuidToImAccount($value['uuid']),//用户名
                'state'=>$value['state'],//用户状态
                'avatar'=>$value['avatar_url'],//用户头像
                'city_id'=>$value['city_id'],//城市id
                'country'=>$value['country']['name'] ?? '',//国家名称
                'country_flag'=>$value['country']['nationalflag'] ?? '',//国家国旗
                'attention'=>$follow_count >=1 ? 1 : 0,//1是已经关注0，是未关注
                'fans_count'=>MemberService::followCount($value['uuid']),//粉丝数
            ];
        }

        //返回处理，有分页或者没分页
        if(isset($param['is_page'])){
            $data['list'] = $list;
            unset($res_arr['data']);
            $data['page_info'] = $res_arr;
            return $data;
        }else{
            return $list;
        }
    }
    
    /**
     * champion_list
     *  'uuid'=>"test-acbb-131231", //用户uuid
        'username'=>"some one name",//用户名
        'work_base'=>"work base",//工作地方
        'work_title'=>"title",//工作经历
        'school_name'=>"school base",//学校
        'school_major'=>"school major",//学习专业
        'avatar'=>"http://xxx.xxx/jpg",//用户头像
        'country'=>"US",//国家名称
        'country_flag'=>"http://xxx.xxx/jpg",//国家国旗
        'attention'=>1, //我对此人的关注状态 1是已经关注，0是未关注
     **/
    public static function championList(array $param = [], $member_uuid = ''){
        $list = null;
        $star_res = Member::where('is_star','=','1')->get();
        if(!empty($star_res)){
            $star_uuid_arr = $star_res->toArray();
            $star_uuid = array_column($star_uuid_arr,'uuid');
        }

        if(empty($star_uuid)){
            return $list;
        }
        // $where[] = ['members_postion_log.postion', '=', 'championList'];
        // $where[] = ['members_postion_log.postion', 'in', $star_uuid];
        $param['limit'] = 4;
        // ::where($where)
        $res = Member::with(['subjects' => function ($query) {
                return $query->select(['member_school.uuid', 'member_school.member_uuid', 'member_school.school_uuid', 
                    'member_school.subject', 'school.name as school_name', 'school.cn_name as school_cn_name'])
                ->join('school', 'member_school.school_uuid', '=', 'school.uuid')
                ->where('school.state', '=', '200')->orderBy('school.id','desc');
            }])
            ->with(['country' => function ($query) {
                return $query->select(['uuid', 'name', 'nationalflag']);
            }])
            ->with(['isFollow' => function ($query) {
                return $query->select(['member_uuid', 'followed_member_uuid', 'is_muted']);
            }])
            ->with(['school' => function ($query) {
                return $query->select(['uuid', 'name', 'cn_name']);
            }])
            ->with(['works' => function ($query) {
                return $query->select(['member_uuid', 'company', 'position']);
            }])
            // ->join('members_postion_log', 'members_postion_log.member_uuid', '=', 'members.uuid')
            ->select('members.uuid','members.nickname','members.avatar_url','members.city_id','members.school_uuid','members.country_uuid','members.state')
            // ->where($where)
            ->whereIn('members.uuid', $star_uuid)
            ->orderBy(\DB::raw('RAND()'))->paginate($param['limit']);

        $res_arr = $res->toArray();
        

        foreach ($res_arr['data'] as $key => $value) {

            // $follow_where = null;
            // $follow_where[] = ['member_uuid', '=', $member_uuid];
            // $follow_where[] = ['followed_member_uuid', '=', $value['uuid']];
            // $follow_count = Follow::where($follow_where)->count();

            $list[] = [
                'uuid'=>$value['uuid'], //用户uuid
                'im_username'=>UtilService::memberUuidToImAccount($value['uuid']),//用户名
                'username'=>$value['nickname'],//用户名
                'state'=>$value['state'],//用户状态
                'work_base'=>$value['works'][0]['company'] ?? null,//工作地方
                'work_title'=>$value['works'][0]['position'] ?? null,//工作经历
                'school_name'=>$value['school']['name'] ?? null,//学校
                'subjects_school_name'=>$value['subjects'][0]['school_name'] ?? null,//学校
                'subjects_school_major'=>$value['subjects'][0]['subject'] ?? null,//专业
                'school_major'=>$value['subjects'][0]['subject'] ?? null,//专业

                'avatar'=>$value['avatar_url'],//用户头像
                'city_id'=>$value['city_id'],//城市id
                'country'=>$value['country']['name'] ?? null,//国家名称
                'country_flag'=>$value['country']['nationalflag'] ?? null,//国家国旗
                'attention'=>MemberService::attention($member_uuid, $value['uuid']),//1是已经关注0，是未关注
            ];
        }
        
        return $list;
    }

    /**
     * more friends
     * @param param[uuid] 圈子uuid
     * @param param[limit] 返回条数
     * @param param[is_page] 是否返回分页
     * 
     * @param member_uuid = 当前用户的uuid
     * more_friends
     *  'uuid'=>"acbb-131231", //用户uuid
        'username'=>"some one name",//用户名
        'avatar'=>"http://xxx.xxx/jpg",//用户头像
        'city_id'=>$value['city_id'],//城市id
        'country'=>'US',//国家名称
        'country_flag'=>'https://xxx.lai.com/123.png',//国家国旗
        'attention'=>1, //我对此人的关注状态 1是已经关注，0是未关注
     **/
    public static function moreFriends(array $param = [], $member_uuid = ''){
        
        $where = null;
        $model = Member::with(['country' => function ($query) {
                return $query->select(['uuid', 'name', 'nationalflag']);
            }])
            ->with(['isFollow' => function ($query) {
                return $query->select(['member_uuid', 'followed_member_uuid', 'is_muted']);
            }])
            ->select('members.id','members.uuid','members.avatar_url','members.nickname',
                'members.city_id','members.country_uuid','members.state',
                'members_attr.uuid as attr_uuid','members_attr.name as attr_name')
            ->join('members_attrs','members_attrs.member_id', '=', 'members.id')
            ->join('members_attr','members_attr.id', '=', 'members_attrs.attr_id')
            ->groupBy('members.id');

        $where[] = ['members.uuid', '<>', $member_uuid];
        if(!empty($param['uuid'])){
            $where[] = ['members_attr.uuid', '=', $param['uuid']];
        }
        $model->where($where); 
        $res = $model->orderBy('id','desc')->paginate($param['limit']);

        $res_arr = $res->toArray();
        $list = null;

        foreach ($res_arr['data'] as $key => $value) {
            $follow_where = null;
            $follow_where[] = ['member_uuid', '=', $member_uuid];
            $follow_where[] = ['followed_member_uuid', '=', $value['uuid']];
            $follow_count = Follow::where($follow_where)->count();

            $list[] = [
                'attr_uuid'=>$value['attr_uuid'],//圈子uuid
                'attr_name'=>$value['attr_name'],//圈子分类
                'uuid'=>$value['uuid'], //用户uuid
                'username'=>$value['nickname'],//用户名
                'im_username'=>UtilService::memberUuidToImAccount($value['uuid']),//用户名
                'state'=>$value['state'],//用户状态
                'avatar'=>$value['avatar_url'],//用户头像
                'city_id'=>$value['city_id'],//城市id
                'country'=>$value['country']['name'] ?? null,//国家名称
                'country_flag'=>$value['country']['nationalflag'] ?? null,//国家国旗
                'attention'=>$follow_count >=1 ? 1 : 0,//1是已经关注0，是未关注
                'fans_count'=>MemberService::followCount($value['uuid']),//粉丝数
            ];
        }
        //返回处理，有分页或者没分页
        if(isset($param['is_page'])){
            $data['list'] = $list;
            unset($res_arr['data']);
            $data['page_info'] = $res_arr;
            return $data;
        }else{
            return $list;
        }
        
    }
    

    /**
     * ad
     *
     **/
    public static function ad(array $param = [], $member_uuid = ''){

        $where[] = ['members_postion_log.postion', '=', 'ad'];
        //::where($where)
        $res = Member::with(['country' => function ($query) {
                return $query->select(['uuid', 'name', 'nationalflag']);
            }])
            // ->with(['friends' => function ($query) {
            //     return $query->select(['member_friend.tab']);
            //     ->join('members', 'members.uuid', '=', 'member_friend.friend_member_uuid')
            //     ->where('members.enabled', '=', 1)
            //     ->orderBy('member_friend.tab', 'desc')
            //     ->limit(2);
            // }])
            ->with(['like' => function  ($query)use($member_uuid) {
                return $query->select(['uuid', 'service_uuid', 'member_uuid', 'place'])->where('member_uuid', '=', $member_uuid);
            }])
            ->with(['isFollow' => function ($query) {
                return $query->select(['member_uuid', 'followed_member_uuid', 'is_muted']);
            }])
            ->join('members_postion_log', 'members_postion_log.member_uuid', '=', 'members.uuid')
            ->select('members.uuid','members.nickname','members.avatar_url','members.city_id', 'members.country_uuid')
            ->selectRaw('(select count(*) as c from member_like where member_like.service_uuid=members.uuid and place = 6) as like_count')
            ->where($where)
            ->orderBy('members.id','desc')->paginate($param['limit']);

        $res_arr = $res->toArray();
        $list = null;

        $member_uuids = [];
        foreach ($res_arr['data'] as $m_key => $m_value) {
            $member_uuids[] = $m_value['uuid'];
        }
        //查找我是否关注这些人
        $attentions = MemberService::batchAttention($member_uuid, $member_uuids);
        $attentions_maps = [];
        if(!empty($attentions)){
            $attentions_maps = array_column($attentions, 'followed_member_uuid', 'followed_member_uuid');
        }
        //查找这些人是否关注我
        $attentionMe = MemberService::batchAttentionMe($member_uuid, $member_uuids);

        //查他们的好友
        $friends_arr = MemberService::batchFriend($member_uuids);

        //查他们的是不是当前登录用户的好友
        $is_my_friends_arr = MemberService::batchIsMyFriend($member_uuid, $member_uuids);
        $my_friends_arr = array_column($is_my_friends_arr, 'friend_member_uuid','friend_member_uuid');

        foreach ($res_arr['data'] as $key => $value) {
            $friends_2 = $friends = [];
            foreach ($friends_arr as $keyf => $valuef) {

                if($valuef['member_uuid'] == $value['uuid']){
                    $friends[] = [
                        'name'=>$valuef['tab'],
                        'uuid'=>$valuef['friend_member_uuid'], //死党uuid
                        'username'=>$valuef['nickname'],//用户名
                        'avatar'=>$valuef['avatar_url'],//死党头像
                    ];
                }
            }
            //随机取两个
            $friends_2 = null;
            if(!empty($friends)){
                if(count($friends) >= 2){
                    $rand_n = 2;
                    $ran_arr = array_rand($friends,$rand_n);

                    foreach ($ran_arr as $f_r_key => $f_r_value) {
                        $friends_2[] = $friends[$f_r_value];
                    }
                }else{
                    $rand_n = 1;
                    $friends_2[] = $friends[0];
                }
                
            }

            $list[] = [
                'uuid'=>$value['uuid'], //用户uuid
                'username'=>$value['nickname'],//用户名
                'im_username'=>UtilService::memberUuidToImAccount($value['uuid']),//用户名
                'avatar'=>$value['avatar_url'],//用户头像
                'partner'=>$friends_2,//用户关系
                'tab'=>$friends_2,//用户关系
                'has_like'=>!empty($value['like']) ? 1 : 0,//1是已经点赞0，是未点赞
                'sum_like'=>$value['like_count'],//喜欢人总数

                // 'uuid'=>$value['uuid'], //用户uuid
                // 'username'=>$value['nickname'],//用户名
                // 'avatar'=>$value['avatar_url'],//用户头像

                'is_friend'=>isset($my_friends_arr[$value['uuid']]) ? 1 : 0,//是否当前登录人的好友 1是0否
                'city_id'=>$value['city_id'],//城市id
                'country'=>$value['country']['name'] ?? '',//国家名称
                'is_followed'=>isset($attentionMe[$value['uuid']]) ? 1 : 0,//此人是否关注登录者
                'country_flag'=>$value['country']['nationalflag'] ?? '',//国家国旗
                'attention'=>isset($attentions_maps[$value['uuid']]) ? 1 : 0,//登录者是否关注此人，1是已经关注0，是未关注
            ];
        }
        
        return $list;
    }
}